<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <todo-header @addToDo="addTodo"></todo-header>
        <todo-list :todos="todos" ></todo-list>
        <todo-footer
          :todos="todos"
          @selectAll="selectAll"
          @clearAll="clearCompleted"
        ></todo-footer>
      </div>
    </div>
  </div>
</template>

<script >
  import header from "./components/header"
  import list from "./components/list"
  import footer from "./components/footer"
  import PubSub from "pubsub-js";
  import Util from './util'
  export default {
    name: 'App',
    data(){
      return {
        todos:[]
      }
    },
    mounted() {
      PubSub.subscribe("deleteTodo",(msg,id)=>{
        this.todos = this.todos.filter((item)=>{
          return item.id !== id
        })
      })
    
      PubSub.subscribe("todoCompleted",(msg,obj)=>{
        this.todos.forEach((item)=>{
          if(item.id === obj.id){
            item.completed = obj.val
          }
        })
      })
  
      this.todos = Util.getTodo()
    },
    methods:{
      addTodo(todo){
        this.todos.unshift(todo)
      },
      selectAll(flag){
        this.todos.forEach((item)=>{
          item.completed = flag
        })
      },
      clearCompleted(){
        this.todos = this.todos.filter((item)=>{
          return !item.completed
        })
      }
      /*clearAll(){
        this.todos.forEach((item)=>{
          item.completed = false
        })
      }*/
    },
    components:{
      "todo-header":header,
      "todo-list":list,
      "todo-footer":footer
    },
    watch:{
      todos: {
        handler(newVal){
          Util.setTodo(newVal)
        },
        deep: true
      }
    }
  }
  
  /*{
    id:0,
    text:"Eating",
    completed:false
  },
  {
    id:1,
    text:"Sleeping",
    completed:false
  },
  {
    id:2,
    text:"Coding",
    completed:false
  },
  {
    id:3,
    text:"Basketball",
    completed:false
  },
  {
    id:4,
    text:"Game",
    completed:false
  }
  */
</script>

<style scoped>
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
</style>
